<script setup lang="ts">
import { DesignPanel, Module, Template } from '@myprint/design';
import { UploadInstance, UploadRawFile } from 'element-plus';

const route = useRouter();

const templateContent = ref('{"width":100,"height":100,"pageUnit":"mm","elementList":[{"type":"Text","x":10,"y":10,"width":50,"height":10,"data":"磨刀霍霍向厨房","option":{"textAlign":"center","verticalAlign":"center"}},{"type":"TextTime","x":10,"y":20,"width":50,"height":10,"option":{"formatter":"{{yyyy年MM月dd日 hh:mm:ss}}","textAlign":"center","verticalAlign":"center"}},{"type":"Image","x":10,"y":30,"width":20,"height":20},{"type":"Image","x":10,"y":30,"width":20,"height":20}]}');

const data = ref({
  template: {
    content: templateContent.value
  } as Template,
  module: null as Module,
  blobList: null
});

const designPanelRef = ref();
const templateCodeEditorRef = ref();
const uploadTemplateRef = ref<UploadInstance>();

const importDialogVisible = ref(false);
const exportDialogVisible = ref(false);

function openImportDialog() {
  templateContent.value = designPanelRef.value?.getTemplate().content;
  importDialogVisible.value = !importDialogVisible.value;
  if (importDialogVisible.value) {
    designPanelRef.value?.unMountedKeyboardEvent();
  } else {
    designPanelRef.value?.mountedKeyboardEvent();
  }
  // 延迟1秒后执行格式化
  setTimeout(() => {
    templateCodeEditorRef.value?.handlePrettier();
  }, 1000);
}

function cancelImportDialog() {
  importDialogVisible.value = false;
  designPanelRef.value?.mountedKeyboardEvent();
}

function openExportDialog() {
  exportDialogVisible.value = !exportDialogVisible.value;
  if (exportDialogVisible.value) {
    designPanelRef.value?.unMountedKeyboardEvent();
  } else {
    designPanelRef.value?.mountedKeyboardEvent();
  }
}

function cancelExportDialog() {
  exportDialogVisible.value = false;
  designPanelRef.value?.mountedKeyboardEvent();
}

function handleImportTemplate(uploadFile: { raw: UploadRawFile }) {
  console.log('handleImportTemplate');
  const file = uploadFile.raw;
  if (!file) {
    console.error('No file selected');
    return false;
  }
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      console.log('handleImportTemplate1');
      const content = e.target?.result as string;
      // 验证是否为有效的JSON
      JSON.parse(content);
      // 更新模板内容
      templateContent.value = content;
      // 格式化代码
      setTimeout(() => {
        templateCodeEditorRef.value?.handlePrettier();
      }, 100);
    } catch (error) {
      console.error('Invalid JSON file:', error);
      // 可以添加错误提示
    }
  };
  reader.readAsText(file);

  // 重置上传组件
  uploadTemplateRef.value.clearFiles();

  // 返回 false 阻止自动上传
  return false;
}

function handleImport() {
  let template = designPanelRef.value?.getTemplate();
  template.content = templateContent.value;
  designPanelRef.value?.setTemplate(template);
  importDialogVisible.value = !importDialogVisible.value;
}

function handleExportJsonFile() {
  // 获取当前模板数据
  const templateContentValue = designPanelRef.value?.getTemplate().content;

  // 将模板内容转换为 JSON
  const templateJsonValue = JSON.parse(templateContentValue, null, 2);

  // 创建 Blob 对象
  const blob = new Blob([templateContentValue], { type: 'application/json' });

  // 创建下载链接
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `${templateJsonValue?.name || 'template'}.json`;

  // 触发下载
  document.body.appendChild(link);
  link.click();

  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

// todo 导出pdf预览文件
function handleExportPdfFile() {
}

</script>

<template>
  <el-space class="design-top-tool" wrap>
    <el-button @click="route.push('/')">返回</el-button>
    <el-button @click="openImportDialog">导入</el-button>
    <el-button @click="openExportDialog">导出</el-button>
  </el-space>
  <!-- 设计面板 -->
  <design-panel ref="designPanelRef"
                :template="data.template"
                class="design-panel-custom"
                :module="{
    provider: JSON.stringify({width: 100, height: 100, pageUnit: 'mm'}),
    previewData: '[{}]'
  }" />

  <!-- 导入窗口 -->
  <el-dialog title="导入" v-model="importDialogVisible" @close="cancelImportDialog">
    <el-upload
      ref="uploadTemplateRef"
      :show-file-list="false"
      :auto-upload="false"
      :limit="1"
      :accept="'.json'"
      :on-change="handleImportTemplate"
      :before-upload="() => false"
    >
      <template #trigger>
        <el-button type="primary">选择JSON文件</el-button>
      </template>
    </el-upload>
    <CodeEditor ref="templateCodeEditorRef" :tab-boolean="false" v-model:text-value="templateContent"
                :prettier="true"></CodeEditor>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelImportDialog">取消</el-button>
        <el-button type="primary" @click="handleImport">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 导出窗口 -->
  <el-dialog title="导出" v-model="exportDialogVisible" @close="cancelExportDialog">
    <!--    <el-button @click="">导出为PDF</el-button>-->
    <el-button @click="handleExportJsonFile">导出为JSON</el-button>
  </el-dialog>
</template>

<style>
.design-top-tool {
  height: 36px;
}

.design-panel-custom {
  position: absolute;
  left: 0;
  top: 36px;
  width: 100%;
  height: calc(100% - 36px);
}
</style>